package com.example.demo.core.advice;

import com.example.demo.domain.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(
		basePackages = {"com.example"}
)
public class RestControllerResultAdvice implements ResponseBodyAdvice<Object> {

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
	}

	@Override
	public Object beforeBodyWrite(Object body,
								  @NonNull MethodParameter methodParameter,
								  @NonNull MediaType mediaType,
								  @NonNull Class<? extends HttpMessageConverter<?>> aClass,
								  @NonNull ServerHttpRequest request,
								  @NonNull ServerHttpResponse response) {
		Object bodyValue;
		if (body instanceof ResponseEntity) {
			bodyValue = ((ResponseEntity<?>)body).getBody();
		} else {
			bodyValue = body;
		}
		Result<?> result;
		if (bodyValue instanceof Result) {
			result = (Result<?>)bodyValue;
		} else {
			result = Result.ok(bodyValue);
		}
		return result;
	}
}
